package com.cyzy.controller;

import com.cyzy.dto.Message;
import com.cyzy.dto.MessageType;
import com.cyzy.sender.ChatProducer;
import com.cyzy.service.MessageService;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/message")
public class MessageConrroller {

    @Autowired
    private MessageService messageService;

    @Autowired
    private ChatProducer chatProducer;
    @RequestMapping("/hello")
    public String hello() {
        return "hello world";
    }
    @PostMapping("/send")
    public String sendMessage(String fromUser, Integer toUserid, String toUser, String content) throws Exception {
        messageService.sendMessage(fromUser, toUserid, toUser, content);
        return "消息发送成功";
    }
    
    @PostMapping("/sendAnnouncement")
    public String sendAnnouncement(@RequestBody Message message) throws Exception {
        List<Integer> toUserids = message.getToUserids();
        String fromUser = message.getFromUser();
        String content = message.getContent();
        String toUser = message.getToUser();
        for (Integer toUserid : toUserids) {
            messageService.sendAnnouncement(fromUser, toUserid, toUser,content);
        }
        return "公告已发送给" + toUserids.size() + "名学生";
    }

    @GetMapping("/getMessage")
    public List<Message> getMessage(Integer toUserid) throws Exception {
        return messageService.getUnreadMessages(toUserid);
    }

    @GetMapping("/getNoMessage")
    public List<Message> getMessageByToUserByisRead(Integer toUserid) throws Exception {
        return messageService.getMessageByToUserByisRead(toUserid);
    }

    @GetMapping("/getMessageById")
    public Message getMessageById(Integer messageId) {
        return messageService.getMessageById(messageId);
    }
    
    @GetMapping("/updateMessageIsRead")
    public String updateMessageIsRead(Integer messageId) throws Exception{
        // 通过发送UPDATE_MESSAGE类型的消息来触发消费者端的更新操作
        Message message = messageService.getMessageById(messageId);
        if (message == null) {
            throw new RuntimeException("消息不存在，ID: " + messageId);
        }
        System.out.println("消息存在");

        messageService.updateMessageIsRead(messageId);

        
        return "消息已发送到队列进行处理: " + messageId;
    }
}